package com.alibaba.spider.util;

import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/10/4 5:21 下午
 */
public class HttpClient {
    public static String sendPostRequest(String url, MultiValueMap<String, String> params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        return setHeader(url, params, client, headers, method);
    }

    public static String sendGetRequest(String url, MultiValueMap<String, String> params, HttpHeaders headers) {
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        return setHeader(url, params, client, headers, method);
    }

    private static String setHeader(String url, MultiValueMap<String, String> params, RestTemplate client, HttpHeaders headers, HttpMethod method) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity entity = new HttpEntity(params, headers);
        ResponseEntity<String> response = client.exchange(url, method, entity, String.class);
        return (String)response.getBody();
    }
}
